<template>
	<div >
		<el-dialog :title="state.title" v-model="state.isShowDialog" width="600px">
			<easy-form :fieldList="fieldList" :model="modelData" ref="formRef" :options="options" ></easy-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default">新 增</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
	import { reactive, toRefs,ref} from 'vue'
	import { rolesApi } from '/@/api/system/role'
	import { success } from '/@/utils/msg'
	import EasyForm from '/@/components/form/index.vue'

	interface RoleState {
		isShowDialog: boolean,
		title:string
	}

	const formRef = ref()
	// form 表单
	const modelData = ref<Record<string, any>>({
		id : 0,
		name : '',
		code : '',
		remark : ''
	})

	// 
	const state = reactive<RoleState>({
		isShowDialog: false,
		title : '新增'
	});


	const fieldList: Form.FieldItem[] = [
		{ label: '角色名称', field: 'name',placeholder:'请输入 角色名称' ,rules:[{ required: true, message: '请输入 角色名称' }]},
		{ label: '角色编码', field: 'code',placeholder:'请输入 角色编码' ,rules:[{ required: true, message: '请输入 角色编码' }]},
		{ label: '备注', field: 'remark',placeholder:'请输入 备注' },
	] 
	
	// Options 配置项
	const options = reactive<Form.Options>({
		showResetButton:false
	})

	// 保存
	const roleSave = async()=> {
		return await rolesApi().save( modelData.value )
	}

	// 打开弹窗
	const openDialog = ( row? : Record<string, any> , title?:string) => {
		modelData.value = row
		state.isShowDialog = true
		state.title = title??'新增'
	}
	// 关闭弹窗
	const closeDialog = () => {
		state.isShowDialog = false;
	};

	// 取消
	const onCancel = () => {
		closeDialog()
	};

	// 
	const emit = defineEmits<{
		(e:"on-load"):void
	}>()

	// 新增
	const onSubmit = async() => {
		if (!formRef) return
		if (formRef.value.validData()) {
			let {code,msg} = await roleSave()
			if ( code === 0 || code === true ) {
				success(msg)
				onCancel()
				emit('on-load')
			}
		} else {
				return false
		}
	}

	const handleBaseSubmit = (model : Record<string, any>) =>{
		console.log(model)
	}
	
	defineExpose({
		openDialog,
		closeDialog,
		onCancel,
		onSubmit,
		handleBaseSubmit,
		fieldList,
		options,
		formRef,
		modelData
	})
</script>
